package cn.hy.threads.transaction;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhaomu
 */
public class SplitUtils {


    /**
     * @param source 数据源
     * @param n      分片个数
     * @param <T>    值
     * @return 切分数据
     */
    public static <T> List<List<T>> averageAssign(List<T> source, int n) {

        List<List<T>> result = new ArrayList<List<T>>();

        int remaider = source.size() % n; // 余数

        int number = source.size() / n;

        int offset = 0;//偏移量

        for (int i = 0; i < n; i++) {

            List<T> subList = null;

            if (remaider > 0) {

                subList = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remaider--;
                offset++;

            } else {
                subList = source.subList(i * number + offset, (i + 1) * number + offset);
            }

            result.add(subList);
        }
        return result;
    }
}
